package org.example.线程;

/**
 * 线程交替打印ABC，各个打印50个
 */
public class 线程交替打印1 {
    private static final Object lock = new Object();
    private static int index = 0;
    private static final int MAX_COUNT = 100;

    public static void main(String[] args) {
        Runnable r1 = ()  -> {
            synchronized (lock){
                while (index < MAX_COUNT){
                    if (index % 3 == 0){
                        System.out.println( index+  " : A");
                        index++;
                        lock.notifyAll();
                    }else{
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }


                }
            }
        };
        Runnable r2 = ()  -> {
            synchronized (lock){
                while (index < MAX_COUNT){
                    if (index % 3 == 1){
                        System.out.println( index+  " : B");
                        index++;
                        lock.notifyAll();
                    }else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        };

        Runnable r3 = ()  -> {
            synchronized (lock){
                while (index < MAX_COUNT){
                    if (index % 3 == 2){
                        System.out.println( index+  " : C");
                        index++;
                        lock.notifyAll();
                    }else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        };

        Thread t1 = new Thread(r1, "thread1");
        Thread t2 = new Thread(r2, "thread2");
        Thread t3 = new Thread(r3, "thread3");
        t1.start();
        t2.start();
        t3.start();
    }

}
